package com.nio.c5_网络编程.aio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @author： pang-yun
 * @date： 2021-09-10 16:14
 * 功能目的 ：用于 aio  异步读取数据
 */
// asynchronous  异步

@Slf4j
public class AioFileChannel {
    public static void main(String[] args) throws IOException {
        try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("asynchronous.txt"), StandardOpenOption.READ)) {

            /*
             * 异步读取的几个参数 ： (ByteBuffer, position, ByteBuffer, CompletionHandler)
             * 参数1 ： ByteBuffer
             * 参数2： 起始位置
             * 参数3 ： 附件 如果不能读取完毕 需要以附件形式返回
             * 参数4： 回调对象 CompletionHandler
             * */
            ByteBuffer buffer = ByteBuffer.allocate(16);
            log.debug("read begin...");
            channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override    //read 读取成功
                public void completed(Integer result, ByteBuffer attachment) {
                    log.debug("read completed...");
                    attachment.flip();
                    while (attachment.hasRemaining()) {
                        byte b = attachment.get();
                        System.out.print((char) b);
                    }
                    System.out.println();
                    attachment.clear();
                }

                @Override   // read 失败
                public void failed(Throwable exc, ByteBuffer attachment) {
                    exc.printStackTrace();
                }
            });
            log.debug("read end...");
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.in.read();   // 先不要让主线程 结束
    }
}

/*
* 16:37:50.309 [main] DEBUG com.nio.c5_网络编程.aio.AioFileChannel - read begin...
16:37:50.314 [main] DEBUG com.nio.c5_网络编程.aio.AioFileChannel - read end...
16:37:50.314 [Thread-4] DEBUG com.nio.c5_网络编程.aio.AioFileChannel - read completed...
asynchronous
*
* 运行结果：  主线程 没有阻塞  直接打印 read end
*
* */